<template>
  <view :class="theme" style="padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);">
    <u-sticky bgColor="#11121b">
      <u-tabs @change="changeTabs" :list="tasks" name="title" height="88" :is-scroll="false" :current="tabCurrent"
        bg-color="#11121b" font-size="28" active-color="#fff" inactive-color="#999"
        :barStyle="{ backgroundColor: `#3b86f6` }" />
    </u-sticky>

    <view class="mt-20">
      <view v-for="(item, index) in tasks[tabCurrent].list" :key="index" class="bg-13 br-12 p-30"
        style="margin: 0 30rpx 20rpx;">
        <view class="fd-row ai-center jc-sb">
          <label>
            <u-image width="108" height="108" :src="item.task_img" />
            <text class="ml-18 color-2 fs-28">{{ item.task_name }}</text>
          </label>
          <button :disabled="!!tabCurrent" @click="submit(index)" hover-class="tap-hover" style="min-width: 150rpx;"
            class="m-0 color-18 bg-5 br-28 fs-28 lh-2 pl-30 pr-30">{{ ["质押", "进行中", "已完成"][tabCurrent] }}</button>
        </view>
        <view class="mt-20 fd-row jc-sb">
          <view class="ai-center">
            <text class="color-2 fs-32">{{ item.join_coin }}</text>
            <text class="mt-8 color-17">质押星核</text>
          </view>
          <view class="ai-center">
            <text class="color-2 fs-32">{{ tabCurrent ? item.limit_times : item.period_time }}</text>
            <text class="mt-8 color-17">{{ tabCurrent ? "剩余周期" : "质押周期" }}(天)</text>
          </view>
          <view class="ai-center">
            <text class="color-2 fs-32">{{ tabCurrent ? (item.has_profit || 0) : (item.profit || 0) }}</text>
            <text class="mt-8 color-17">{{ tabCurrent ? "收益" : "每日收益" }}</text>
          </view>
          <view v-if="!+tabCurrent" class="ai-center">
            <text class="color-2 fs-32">{{ item.allprofit || 0 }}</text>
            <text class="mt-8 color-17">总产量</text>
          </view>
        </view>
        <label v-if="tabCurrent" class="mt-40 jc-center color-18">质押时间：{{ item.create_time }}</label>
      </view>
    </view>

    <view v-if="tabCurrent === 1" class="fixed bottom-0 jc-sb bg-1"
      style="padding-bottom: env(safe-area-inset-bottom); box-sizing: content-box; left: var(--window-left); right: var(--window-right);">
      <button @click="beforeReceive" hover-class="tap-hover" style="margin: 30rpx; line-height: 88rpx;"
        class="bg-6 br-10 color-2 text-center fs-32">
        领取收益
      </button>
    </view>

    <view class="mt-30 mb-30 ai-center">
      <u-image v-if="!tasks[tabCurrent].list.length" :showLoading="false" width="400" height="400" class="mt-60 mb-30"
        src="/static/img/blank.png" mode="aspectFit" />
      <u-loadmore :status="tasks[tabCurrent].cache.status" />
    </view>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { debounce, pager } from "@/common/libs/utils";
import { onLoad, onPullDownRefresh, onReady } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);

const tasks = reactive([
  {
    title: "全部星球",
    api: "/packList",
    type: null,
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 0,
    next: false,
  },
  {
    title: "进行中",
    api: "/myTask",
    type: 1,
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 5,
    next: false,
  },
  {
    title: "已完成",
    api: "/myTask",
    type: 0,
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 1,
    next: false,
  },
]);
const refs = {
  adRewardedVideo: {} as UniApp.RewardedVideoAdContext,
  adInterstitial: {} as UniApp.InterstitialAdContext
};
let _isLoaded = false;

const tabCurrent = ref(0);
const changeTabs = (index: number) => {
  if (index === tabCurrent.value) return;
  const item = tasks[tabCurrent.value];
  if (item.cache.status === "loading") return;
  tabCurrent.value = index;
  item.page = 0; item.cache.page = 1;
  getData();
}

onLoad(() => {
  getData();
});

onReady(() => {
  refs.adRewardedVideo = uni.createRewardedVideoAd({
    adpid: '1759662325',
  });
  refs.adInterstitial = uni.createInterstitialAd({
    adpid: '1035559566'
  });

  refs.adRewardedVideo.onLoad((e) => {
    console.log(e);
  });
  refs.adRewardedVideo.onError((e) => {
    if (e && e.errMsg) { _isLoaded = false; }
  });
  refs.adRewardedVideo.onClose((e) => {
    _isLoaded = false;
    if (e && e.isEnded) {
      receive();
      return;
    }
    uni.showModal({ title: "温馨提示", content: "观看完成广告即可领取收益", showCancel: false });
  });
});

onPullDownRefresh(() => {
  const item = tasks[tabCurrent.value];
  item.page = 0; item.cache.page = 1;
  getData();
  setTimeout(uni.stopPullDownRefresh, 360);
})

const getData = () => {
  const { api: url, type } = tasks[tabCurrent.value];
  pager({ url, data: { type } }, tasks[tabCurrent.value]);
}

const submit = (index: number) => {
  const { id, task_name } = tasks[tabCurrent.value].list[index];
  uni.showModal({
    title: "温馨提示",
    content: `确认后即可开始领取收益，确认要质押【${task_name}】吗？`,
    success({ cancel }) {
      if (cancel) return;
      uni.request({
        url: "/joinTask",
        data: { id },
        success({ msg: title }: any) {
          uni.showToast({ title });
        }
      });
    }
  });
}

const beforeReceive = debounce(() => {
  // #ifdef APP-PLUS
  if (!_isLoaded) {
    _isLoaded = true;
    refs.adRewardedVideo.show().catch(res => receive());
    refs.adInterstitial.show();
  }
  // #endif

  // #ifndef APP-PLUS
  uni.showToast({ title: "请在App端操作", icon: "none" });
  // #endif
});

const receive = () => {
  uni.request({
    url: "/receiveTask",
    success({ msg: content }: any) {
      uni.showModal({ content, showCancel: false });
      uni.startPullDownRefresh();
    }
  })
}

</script>
<style>
page {
  background-color: #11121b;
}
</style>
<style lang="scss" scoped>
// scss
</style>